<template>
  <div class="question-list">
    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form :model="searchForm" layout="horizontal">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="id" label="题目ID">
              <a-input-number
                v-model="searchForm.id"
                placeholder="请输入题目ID"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="title" label="题目标题">
              <a-input v-model="searchForm.title" placeholder="请输入标题" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="tags" label="题目标签">
              <a-input-tag
                v-model="searchForm.tags"
                placeholder="请输入标签，按下回车确认"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="loadData">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="action-card">
      <a-row>
        <a-col :span="24" style="text-align: left">
          <a-space>
            <a-button type="primary" @click="toCreateQuestion">
              <template #icon>
                <icon-plus />
              </template>
              新增题目
            </a-button>
            <a-button
              type="primary"
              status="danger"
              @click="batchDelete"
              :disabled="selectedKeys.length === 0"
            >
              <template #icon>
                <icon-delete />
              </template>
              批量删除
            </a-button>
            <a-button @click="loadData">
              <template #icon>
                <icon-refresh />
              </template>
              刷新
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 题目表格 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data="questionList"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 标题 -->
        <template #title="{ record }">
          <a-link @click="viewQuestion(record)">{{ record.title }}</a-link>
        </template>

        <!-- 标签 -->
        <template #tags="{ record }">
          <div class="tags-container">
            <a-tag
              v-for="tag in parseTags(record.tags)"
              :key="tag"
              color="blue"
              bordered
            >
              {{ tag }}
            </a-tag>
          </div>
        </template>

        <!-- 通过率 -->
        <template #acceptRate="{ record }">
          <a-progress
            :percent="calculateAcceptRate(record)"
            :status="getAcceptRateStatus(record)"
            :show-text="true"
          />
        </template>

        <!-- 状态 -->
        <template #isDelete="{ record }">
          <a-tag v-if="record.isDelete === 0" color="green">正常</a-tag>
          <a-tag v-else-if="record.isDelete === 1" color="red">已删除</a-tag>
        </template>

        <!-- 操作列 -->
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="toEditQuestion(record)">
              编辑
            </a-button>
            <a-button type="text" size="small" @click="viewSubmits(record)">
              提交记录
            </a-button>
            <a-button
              type="text"
              size="small"
              status="danger"
              @click="confirmDelete(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  QuestionControllerService,
  DeleteRequest,
} from "../../../../generated";
import { Message, Modal } from "@arco-design/web-vue";
import { useRouter } from "vue-router";

const router = useRouter();

// 表格列定义
const columns = [
  { title: "ID", dataIndex: "id", width: 80 },
  { title: "标题", dataIndex: "title", slotName: "title" },
  { title: "标签", dataIndex: "tags", slotName: "tags", width: 240 },
  { title: "提交数", dataIndex: "submitNum", width: 100 },
  { title: "通过数", dataIndex: "acceptedNum", width: 100 },
  { title: "通过率", slotName: "acceptRate", width: 140 },
  { title: "创建时间", dataIndex: "createTime", width: 180 },
  { title: "状态", dataIndex: "isDelete", slotName: "isDelete", width: 80 },
  {
    title: "操作",
    dataIndex: "operations",
    slotName: "operations",
    width: 200,
    fixed: "right",
  },
];

// 搜索表单数据
const searchForm = reactive({
  id: undefined as number | undefined,
  title: "",
  tags: [] as string[],
  current: 1,
  pageSize: 10,
});

// 题目列表数据
const questionList = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedKeys = ref<number[]>([]);

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表格选择配置
const rowSelection = {
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
  onChange: (selectedRowKeys: number[]) => {
    selectedKeys.value = selectedRowKeys;
  },
};

// 解析标签
const parseTags = (tagsStr: string) => {
  if (!tagsStr) {
    return [];
  }
  try {
    return JSON.parse(tagsStr);
  } catch (error) {
    return [];
  }
};

// 计算通过率
const calculateAcceptRate = (record: any) => {
  if (!record.submitNum || record.submitNum <= 0) {
    return 0;
  }
  return Math.round((record.acceptedNum / record.submitNum) * 100);
};

// 获取通过率状态
const getAcceptRateStatus = (record: any) => {
  const rate = calculateAcceptRate(record);
  if (rate >= 70) {
    return "success";
  }
  if (rate >= 40) {
    return "normal";
  }
  return "danger";
};

// 加载题目数据
const loadData = async () => {
  loading.value = true;
  try {
    // 准备请求参数，确保tags是数组
    const req = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    };

    const res = await QuestionControllerService.listQuestionByPageUsingPost(
      req
    );

    if (res.code === 0 && res.data) {
      questionList.value = res.data.records || [];
      total.value = res.data.total || 0;
      pagination.total = total.value;
    } else {
      Message.error("获取题目列表失败：" + (res.message || "系统错误"));
    }
  } catch (error) {
    Message.error("获取题目列表失败：" + error);
  } finally {
    loading.value = false;
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.id = undefined;
  searchForm.title = "";
  searchForm.tags = [];
  pagination.current = 1;
  loadData();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  loadData();
};

// 跳转到创建题目页面
const toCreateQuestion = () => {
  router.push("/add/question");
};

// 跳转到编辑题目页面
const toEditQuestion = (record: any) => {
  router.push({
    path: "/update/question",
    query: {
      id: record.id,
    },
  });
};

// 查看题目详情
const viewQuestion = (record: any) => {
  router.push({
    path: `/view/question/${record.id}`,
  });
};

// 查看提交记录
const viewSubmits = (record: any) => {
  router.push({
    path: "/question_submit",
    query: {
      questionId: record.id,
    },
  });
};

// 确认删除题目
const confirmDelete = (record: any) => {
  Modal.warning({
    title: "确认删除",
    content: `确定要删除题目 "${record.title}" 吗？`,
    okButtonProps: { status: "danger" },
    onOk: () => deleteQuestion(record.id),
  });
};

// 删除题目
const deleteQuestion = async (id: number) => {
  try {
    const res = await QuestionControllerService.deleteQuestionUsingPost({
      id,
    } as DeleteRequest);
    if (res.code === 0) {
      Message.success("删除成功");
      loadData();
    } else {
      Message.error("删除失败: " + (res.message || "系统错误"));
    }
  } catch (error) {
    Message.error("删除失败: " + error);
  }
};

// 批量删除题目
const batchDelete = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning("请选择要删除的题目");
    return;
  }

  Modal.warning({
    title: "批量删除",
    content: `确定要删除选中的 ${selectedKeys.value.length} 个题目吗？`,
    okButtonProps: { status: "danger" },
    onOk: async () => {
      try {
        // 实际开发中应该有批量删除接口
        let failCount = 0;
        for (const id of selectedKeys.value) {
          const res = await QuestionControllerService.deleteQuestionUsingPost({
            id,
          } as DeleteRequest);
          if (res.code !== 0) {
            failCount++;
          }
        }

        if (failCount === 0) {
          Message.success("批量删除成功");
        } else {
          Message.warning(
            `部分题目删除失败，成功删除 ${
              selectedKeys.value.length - failCount
            } 个，失败 ${failCount} 个`
          );
        }

        selectedKeys.value = [];
        loadData();
      } catch (error) {
        Message.error("批量删除失败: " + error);
      }
    },
  });
};

// 组件挂载后加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.question-list {
  padding: 0;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 16px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
</style>
